package repository

import (
	"context"
	"database/sql"
	"encoding/json"
	"fmt"
	"strings"
	"time"

	"mall/common/globalkey"
	"mall/common/modelx"
	"mall/service/promotion/model"

	// "github.com/sirupsen/logrus"
	"github.com/volatiletech/null/v8"
	"github.com/volatiletech/sqlboiler/v4/boil"
	"github.com/volatiletech/sqlboiler/v4/queries/qm"
	"github.com/zeromicro/go-zero/core/stores/cache"
)

type (
	// CouponTemplateRepository is an interface to be customized, add more methods here,
	// and implement the added methods in customCouponTemplateRepository.
	CouponTemplateRepository interface {
		FindOne(ctx context.Context, id uint64) (*model.PromotionCouponTemplate, error)
		FindOneByName(ctx context.Context, name string) (*model.PromotionCouponTemplate, error)
		FindOneWithExpire(
			ctx context.Context,
			id uint64,
			expire time.Duration,
		) (*model.PromotionCouponTemplate, error) // ##25.03.04##
		FindOneNoCache(
			ctx context.Context,
			conn boil.ContextExecutor,
			id uint64,
		) (*model.PromotionCouponTemplate, error) // ##25.03.04##
		GetList(
			ctx context.Context,
			cols model.M,
			withCount int,
			filter map[string]map[string][]any,
		) ([]*model.PromotionCouponTemplate, int64, error) // ##25.03.01##
		Insert(
			ctx context.Context,
			tx boil.ContextExecutor,
			data *model.PromotionCouponTemplate,
			rel *model.PromotionCouponRel,
		) error // ##25.03.01##
		Update(
			ctx context.Context,
			tx boil.ContextExecutor,
			data *model.PromotionCouponTemplate,
			rel *model.PromotionCouponRel,
		) error // ##25.03.04##
		UpdateBatch(ctx context.Context, tx boil.ContextExecutor, ids []uint64, cols model.M) error
		SoftDelete(ctx context.Context, tx boil.ContextExecutor, id uint64) error  // ##25.03.04##
		Restore(ctx context.Context, tx boil.ContextExecutor, id uint64) error     // ##25.03.04##
		ForceDelete(ctx context.Context, tx boil.ContextExecutor, id uint64) error // ##25.03.04##
		ForceDeleteBatch(ctx context.Context, tx boil.ContextExecutor, ids []uint64) error
		GetProductList(
			ctx context.Context,
			cols model.M,
			withCount int,
			filter map[string]map[string][]any,
		) ([]*model.PromotionCouponProductRelationship, int64, error) // deprecated
		GetProductBrandList(
			ctx context.Context,
			cols model.M,
			withCount int,
			filter map[string]map[string][]any,
		) ([]*model.PromotionCouponProductBrandRelationship, int64, error) // deprecated
		GetProductCategoryList(
			ctx context.Context,
			cols model.M,
			withCount int,
			filter map[string]map[string][]any,
		) ([]*model.PromotionCouponProductCategoryRelationship, int64, error) // deprecated
		UpdateBindRel(
			ctx context.Context,
			tx boil.ContextExecutor,
			id uint64,
			rel *model.PromotionCouponBindRel,
		) error // deprecated

		AttachProductToCoupon(
			ctx context.Context,
			tx boil.ContextExecutor,
			data *model.CouponProductRelationship,
		) error // ##25.03.08##
		DetachProductFromCoupon(
			ctx context.Context,
			tx boil.ContextExecutor,
			filter map[string]map[string][]any,
		) error // ##25.03.08##
		GetRelProductList(
			ctx context.Context,
			cols model.M,
			withCount int,
			filter map[string]map[string][]any,
		) ([]*model.CouponProductRelationship, int64, error) // ##25.03.08##

		GetMedia(
			ctx context.Context,
			cols model.M,
			withCount int,
			filter map[string]map[string][]any,
		) ([]*model.PromotionAttachmentRelationship, int64, error) // ##25.03.01##
		GetMeta(
			ctx context.Context,
			cols model.M,
			withCount int,
			filter map[string]map[string][]any,
		) ([]*model.PromotionCouponMetum, int64, error) // ##25.03.01##
	}

	customCouponTemplateRepository struct {
		modelx.CachedConn
		mysqlConn           *sql.DB
		cacheIdPrefix       string
		cacheNamePrefix     string
		cacheIdExpirePrefix string
	}
)

// NewCouponTemplateRepository returns a repository for the database table.
func NewCouponTemplateRepository(mysqlConn *sql.DB, cacheConf cache.CacheConf) CouponTemplateRepository {
	return &customCouponTemplateRepository{
		CachedConn:          modelx.NewConn(mysqlConn, cacheConf),
		mysqlConn:           mysqlConn,
		cacheIdPrefix:       "cache:promotion:coupons:id:",
		cacheNamePrefix:     "cache:promotion:coupons:name:",
		cacheIdExpirePrefix: "cache:promotion:coupons:id:expire:",
	}
}

func (r *customCouponTemplateRepository) FindOne(
	ctx context.Context,
	id uint64,
) (*model.PromotionCouponTemplate, error) {
	cacheIdKey := r.formatPrimary(id)
	var resp model.PromotionCouponTemplate
	err := r.QueryCtx(ctx, &resp, cacheIdKey, func(ctx context.Context, conn *sql.DB, v any) error {
		data, err := model.FindPromotionCouponTemplate(ctx, conn, id)
		if err != nil {
			return err
		}

		*v.(*model.PromotionCouponTemplate) = *data

		return nil
	})

	switch err {
	case nil:
		return &resp, nil
	case sql.ErrNoRows:
		return nil, model.ErrNotFound
	default:
		return nil, err
	}
}

func (r *customCouponTemplateRepository) FindOneByName(
	ctx context.Context,
	name string,
) (*model.PromotionCouponTemplate, error) {
	cacheNameKey := r.formatNameKey(name)
	var resp model.PromotionCouponTemplate
	err := r.QueryRowIndexCtx(ctx, &resp, cacheNameKey, r.formatPrimary,
		func(ctx context.Context, conn *sql.DB, v any) (i any, e error) {
			mods := []qm.QueryMod{
				model.PromotionCouponTemplateWhere.Name.EQ(name),
			}
			list, err := model.PromotionCouponTemplates(mods...).All(ctx, conn)
			if err != nil {
				return nil, err
			}

			*v.(*model.PromotionCouponTemplate) = *list[0]

			return list[0].ID, nil
		}, r.queryPrimary)

	switch err {
	case nil:
		return &resp, nil
	case sql.ErrNoRows:
		return nil, model.ErrNotFound
	default:
		return nil, err
	}
}

func (r *customCouponTemplateRepository) FindOneWithExpire(
	ctx context.Context,
	id uint64,
	expire time.Duration,
) (*model.PromotionCouponTemplate, error) {
	cacheIdKey := r.formatPrimary(id)
	var resp model.PromotionCouponTemplate
	err := r.QueryWithExpireCtx(ctx, &resp, cacheIdKey, expire, func(ctx context.Context, conn *sql.DB, v any) error {
		data, err := model.FindPromotionCouponTemplate(ctx, conn, id)
		if err != nil {
			return err
		}

		*v.(*model.PromotionCouponTemplate) = *data

		return nil
	})

	switch err {
	case nil:
		return &resp, nil
	case sql.ErrNoRows:
		return nil, model.ErrNotFound
	default:
		return nil, err
	}
}

func (r *customCouponTemplateRepository) FindOneNoCache(
	ctx context.Context,
	conn boil.ContextExecutor,
	id uint64,
) (*model.PromotionCouponTemplate, error) {
	var db boil.ContextExecutor = r.mysqlConn
	if conn != nil {
		db = conn
	}
	data, err := model.FindPromotionCouponTemplate(ctx, db, id)
	// logrus.Info(fmt.Sprintf("FindOneNoCache err: %+v", err))
	switch err {
	case nil:
		return data, nil
	case sql.ErrNoRows:
		return nil, model.ErrNotFound
	default:
		return nil, err
	}
}

func (r *customCouponTemplateRepository) GetList(
	ctx context.Context,
	cols model.M,
	withCount int,
	filter map[string]map[string][]any,
) (list []*model.PromotionCouponTemplate, count int64, err error) {
	var page int
	var pageSize int
	var limit int
	var selectCol string
	var mods []qm.QueryMod
	var nextCount int64
	var previousCount int64
	var statistic bool
	for k, v := range cols {
		switch k {
		case "page":
			if val, ok := v.(uint64); ok && val > 1 {
				page = int(val)
			}
		case "pageSize":
			if val, ok := v.(uint64); ok && val > 0 {
				pageSize = int(val)
			}
		case "limit":
			if val, ok := v.(uint32); ok && val > 0 {
				limit = int(val)
			}
		case "offset":
			if withCount == 2 {
				if val, ok := v.(uint32); ok && val > 0 {
					mods = append(mods, qm.Offset(int(val)))
					previousCount = 1
				}
			}
		case "orderBy":
			if val, ok := v.(string); ok && len(val) > 0 {
				mods = append(mods, qm.OrderBy(val))
			}
		case "preMinId":
			if withCount == 3 {
				if val, ok := v.(uint64); ok && val > 0 {
					mods = append(mods, qm.OrderBy(model.PromotionCouponTemplateColumns.ID+" DESC"))
					mods = append(mods, model.PromotionCouponTemplateWhere.ID.LT(val))
					previousCount = 1
				}
			}
		case "preMaxId":
			if withCount == 4 {
				if val, ok := v.(uint64); ok && val > 0 {
					mods = append(mods, qm.OrderBy(model.PromotionCouponTemplateColumns.ID+" ASC"))
					mods = append(mods, model.PromotionCouponTemplateWhere.ID.GT(val))
					previousCount = 1
				}
			}
		case "select":
			if withCount != 5 {
				if val, ok := v.(string); ok && len(val) > 0 {
					selectCol = val
				}
			}
		case "search":
			if val, ok := v.(string); ok && len(val) > 0 { // 搜索
				likeVal := fmt.Sprintf("%%%s%%", val)
				mods = append(mods, qm.Where(fmt.Sprintf(
					"%s LIKE ?",
					model.PromotionCouponTemplateColumns.Name), likeVal))
			}
		case "statistic":
			if val, ok := v.(string); ok && val == "1" { // 按 Status 统计
				statistic = true
			}
		}
	}

	for key, opMap := range filter {
		switch key {
		case model.PromotionCouponTemplateColumns.ID:
			mods = append(mods, modelx.GetIntMods(model.PromotionCouponTemplateColumns.ID, opMap)...)
		case model.PromotionCouponTemplateColumns.Name:
			mods = append(mods, modelx.GetStringMods(model.PromotionCouponTemplateColumns.Name, opMap)...)
		case model.PromotionCouponTemplateColumns.CouponType:
			mods = append(mods, modelx.GetIntMods(model.PromotionCouponTemplateColumns.CouponType, opMap)...)
		case model.PromotionCouponTemplateColumns.MutexType:
			mods = append(mods, modelx.GetIntMods(model.PromotionCouponTemplateColumns.MutexType, opMap)...)
		case model.PromotionCouponTemplateColumns.Sort:
			mods = append(mods, modelx.GetIntMods(model.PromotionCouponTemplateColumns.Sort, opMap)...)
		case model.PromotionCouponTemplateColumns.ScopeType:
			mods = append(mods, modelx.GetIntMods(model.PromotionCouponTemplateColumns.ScopeType, opMap)...)
		case model.PromotionCouponTemplateColumns.Mode:
			mods = append(mods, modelx.GetIntMods(model.PromotionCouponTemplateColumns.Mode, opMap)...)
		case model.PromotionCouponTemplateColumns.Threshhold:
			mods = append(mods, modelx.GetIntMods(model.PromotionCouponTemplateColumns.Threshhold, opMap)...)
		case model.PromotionCouponTemplateColumns.DiscountMode:
			mods = append(mods, modelx.GetIntMods(model.PromotionCouponTemplateColumns.DiscountMode, opMap)...)
		case model.PromotionCouponTemplateColumns.DiscountValue:
			mods = append(mods, modelx.GetIntMods(model.PromotionCouponTemplateColumns.DiscountValue, opMap)...)
		case model.PromotionCouponTemplateColumns.GemPrice:
			mods = append(mods, modelx.GetIntMods(model.PromotionCouponTemplateColumns.GemPrice, opMap)...)
		case model.PromotionCouponTemplateColumns.Count:
			mods = append(mods, modelx.GetIntMods(model.PromotionCouponTemplateColumns.Count, opMap)...)
		case model.PromotionCouponTemplateColumns.PerLimit:
			mods = append(mods, modelx.GetIntMods(model.PromotionCouponTemplateColumns.PerLimit, opMap)...)
		case model.PromotionCouponTemplateColumns.ExpireMode:
			mods = append(mods, modelx.GetIntMods(model.PromotionCouponTemplateColumns.ExpireMode, opMap)...)
		case model.PromotionCouponTemplateColumns.ExpireValue:
			mods = append(mods, modelx.GetIntMods(model.PromotionCouponTemplateColumns.ExpireValue, opMap)...)
		case model.PromotionCouponTemplateColumns.Status:
			mods = append(mods, modelx.GetIntMods(model.PromotionCouponTemplateColumns.Status, opMap)...)
		case model.PromotionCouponTemplateColumns.Remark:
			mods = append(mods, modelx.GetStringMods(model.PromotionCouponTemplateColumns.Remark, opMap)...)
		case model.PromotionCouponTemplateColumns.ApplyStartedAt:
			mods = append(mods, modelx.GetTimeMods(model.PromotionCouponTemplateColumns.ApplyStartedAt, opMap)...)
		case model.PromotionCouponTemplateColumns.ApplyEndedAt:
			mods = append(mods, modelx.GetTimeMods(model.PromotionCouponTemplateColumns.ApplyEndedAt, opMap)...)
		case model.PromotionCouponTemplateColumns.StartedAt:
			mods = append(mods, modelx.GetTimeMods(model.PromotionCouponTemplateColumns.StartedAt, opMap)...)
		case model.PromotionCouponTemplateColumns.EndedAt:
			mods = append(mods, modelx.GetTimeMods(model.PromotionCouponTemplateColumns.EndedAt, opMap)...)
		case model.PromotionCouponTemplateColumns.CreatedAt:
			mods = append(mods, modelx.GetTimeMods(model.PromotionCouponTemplateColumns.CreatedAt, opMap)...)
		case model.PromotionCouponTemplateColumns.UpdatedAt:
			mods = append(mods, modelx.GetTimeMods(model.PromotionCouponTemplateColumns.UpdatedAt, opMap)...)
		case model.PromotionCouponTemplateColumns.DeletedAt:
			mods = append(mods, modelx.GetTimeMods(model.PromotionCouponTemplateColumns.DeletedAt, opMap)...)
		}
	}

	if statistic {
		mods = append(mods, qm.Select(fmt.Sprintf(
			"%s, count(%s) as %s",
			model.PromotionCouponTemplateColumns.Status,
			model.PromotionCouponTemplateColumns.Status,
			model.PromotionCouponTemplateColumns.Sort,
		)))
		mods = append(mods, qm.GroupBy(model.PromotionCouponTemplateColumns.Status))
		preList, preErr := model.PromotionCouponTemplates(mods...).All(ctx, r.mysqlConn)
		if preErr != nil {
			err = preErr
			return
		}

		return preList, 0, nil
	}

	if withCount >= 2 {
		if limit > 0 {
			mods = append(mods, qm.Limit(limit+1))
		}
	} else if withCount >= 0 {
		count, err = model.PromotionCouponTemplates(mods...).Count(ctx, r.mysqlConn)
		if err != nil {
			return
		}

		if withCount == 0 {
			return
		}
	}

	if pageSize > 0 && (withCount == -1 || withCount == 1) {
		if page > 1 {
			mods = append(mods, qm.Offset(pageSize*(page-1)))
		}
		mods = append(mods, qm.Limit(pageSize))
	}

	var columns []string
	if len(selectCol) > 0 {
		if selectCol == "," {
			columns = append(columns, model.PromotionCouponTemplateColumns.ID)
		} else {
			columns = strings.Split(selectCol, ",")
		}
	}
	if len(columns) > 0 {
		mods = append(mods, qm.Select(columns...))
	}

	list, err = model.PromotionCouponTemplates(mods...).All(ctx, r.mysqlConn)
	if err != nil {
		return
	}

	if withCount >= 2 {
		if limit > 0 && len(list) > limit {
			nextCount = 1
			list = list[:limit]
		}
		count = previousCount + nextCount*2
	}

	return
}

func (r *customCouponTemplateRepository) Insert(
	ctx context.Context,
	tx boil.ContextExecutor,
	data *model.PromotionCouponTemplate,
	rel *model.PromotionCouponRel,
) error {
	err := r.ExecCtx(ctx, func(ctx context.Context, conn *sql.DB) error {
		var db boil.ContextExecutor
		if tx != nil {
			db = tx
		} else {
			db = conn
		}

		err := data.Insert(ctx, db, boil.Infer())
		if err != nil {
			return err
		}

		if rel == nil {
			return nil
		}

		tmplId := data.ID

		if len(rel.Meta) > 0 {
			for _, v := range rel.Meta {
				v.CouponTemplateID = tmplId
				err = v.Insert(ctx, db, boil.Infer())
				if err != nil {
					return err
				}
			}
		}

		if len(rel.Media) > 0 {
			for _, v := range rel.Media {
				v.ObjectID = tmplId
				v.ObjectType = uint16(globalkey.AttachmentLogTypePromotionCoupon)
				err = v.Insert(ctx, db, boil.Infer())
				if err != nil {
					return err
				}
			}
		}

		return nil
	}, r.getCacheKeys(data)...)

	return err
}

func (r *customCouponTemplateRepository) Update(
	ctx context.Context,
	tx boil.ContextExecutor,
	data *model.PromotionCouponTemplate,
	rel *model.PromotionCouponRel,
) error {
	err := r.ExecCtx(ctx, func(ctx context.Context, conn *sql.DB) error {
		var db boil.ContextExecutor
		if tx != nil {
			db = tx
		} else {
			db = conn
		}

		blacklist := []string{
			model.PromotionCouponTemplateColumns.ID,
			model.PromotionCouponTemplateColumns.DeletedAt,
		}
		if rel != nil && len(rel.Blacklist) > 0 {
			blacklist = append(blacklist, rel.Blacklist...)
		}
		rowsAff, err := data.Update(ctx, db, boil.Blacklist(blacklist...))
		if err != nil {
			return err
		}

		if rowsAff == 0 {
			return model.ErrNotUpdated
		}

		if rel == nil {
			return nil
		}

		tmplId := data.ID

		if len(rel.Meta) > 0 {
			for _, v := range rel.Meta {
				if v.MetaID > 0 {
					_, err = v.Update(ctx, db, boil.Blacklist(
						model.PromotionCouponMetumColumns.MetaID,
						model.PromotionCouponMetumColumns.CouponTemplateID,
						model.PromotionCouponMetumColumns.MetaKey,
					))
					if err != nil {
						return err
					}
				} else {
					v.CouponTemplateID = tmplId
					err = v.Insert(ctx, db, boil.Infer())
					if err != nil {
						return err
					}
				}
			}
		}

		if len(rel.Media) > 0 {
			for _, v := range rel.Media {
				if v.AttachmentRelationshipID > 0 {
					_, err = v.Update(ctx, db, boil.Blacklist(
						model.PromotionAttachmentRelationshipColumns.AttachmentRelationshipID,
						model.PromotionAttachmentRelationshipColumns.ObjectID,
						model.PromotionAttachmentRelationshipColumns.ObjectType,
						model.PromotionAttachmentRelationshipColumns.AttachmentID,
					))
					if err != nil {
						return err
					}
				} else {
					v.ObjectID = tmplId
					v.ObjectType = uint16(globalkey.AttachmentLogTypePromotionCoupon)
					err = v.Insert(ctx, db, boil.Infer())
					if err != nil {
						return err
					}
				}
			}
		}

		if len(rel.DelMetaIds) > 0 {
			var mods []qm.QueryMod
			mods = append(mods, model.PromotionCouponMetumWhere.MetaID.IN(rel.DelMetaIds))
			_, err = model.PromotionCouponMeta(mods...).DeleteAll(ctx, db)
			if err != nil {
				return err
			}
		}

		if len(rel.DelMediaIds) > 0 {
			var mods []qm.QueryMod
			mods = append(mods, model.PromotionAttachmentRelationshipWhere.AttachmentRelationshipID.IN(rel.DelMediaIds))
			_, err = model.PromotionAttachmentRelationships(mods...).DeleteAll(ctx, db)
			if err != nil {
				return err
			}
		}

		return nil
	}, r.getCacheKeys(data)...)

	return err
}

func (r *customCouponTemplateRepository) UpdateBatch(
	ctx context.Context,
	tx boil.ContextExecutor,
	ids []uint64,
	cols model.M,
) error {
	if len(ids) > 0 {
		err := r.ExecCtx(ctx, func(ctx context.Context, conn *sql.DB) error {
			var db boil.ContextExecutor
			if tx != nil {
				db = tx
			} else {
				db = conn
			}

			var mods []qm.QueryMod
			mods = append(mods, model.PromotionCouponTemplateWhere.ID.IN(ids))

			rowsAff, err := model.PromotionCouponTemplates(mods...).UpdateAll(ctx, db, cols)
			if err != nil {
				return err
			}

			if rowsAff == 0 {
				return model.ErrNotUpdated
			}

			return nil
		}, r.formatPrimaries(ids)...)

		return err
	}

	return nil
}

func (r *customCouponTemplateRepository) SoftDelete(
	ctx context.Context,
	tx boil.ContextExecutor,
	id uint64,
) error {
	data, err := r.FindOneNoCache(ctx, tx, id)
	if err != nil {
		if err == model.ErrNotFound {
			return nil
		}

		return err
	}

	if data.Status == uint16(globalkey.StatusDeleted) {
		return nil
	}

	data.DelStatus = data.Status
	data.Status = uint16(globalkey.StatusDeleted)
	data.DeletedAt = null.TimeFrom(time.Now())
	err = r.ExecCtx(ctx, func(ctx context.Context, conn *sql.DB) error {
		var db boil.ContextExecutor
		if tx != nil {
			db = tx
		} else {
			db = conn
		}

		rowsAff, err := data.Update(ctx, db, boil.Whitelist(
			model.PromotionCouponTemplateColumns.Status,
			model.PromotionCouponTemplateColumns.DelStatus,
			model.PromotionCouponTemplateColumns.DeletedAt,
		))
		if err != nil {
			return err
		}

		if rowsAff == 0 {
			return model.ErrNotUpdated
		}

		return nil
	}, r.getCacheKeys(data)...)

	return err
}

func (r *customCouponTemplateRepository) Restore(
	ctx context.Context,
	tx boil.ContextExecutor,
	id uint64,
) error {
	data, err := r.FindOneNoCache(ctx, tx, id)
	if err != nil {
		if err == model.ErrNotFound {
			return nil
		}

		return err
	}

	if data.Status != uint16(globalkey.StatusDeleted) {
		return nil
	}

	data.Status = data.DelStatus
	data.DeletedAt = null.TimeFromPtr(nil)
	err = r.ExecCtx(ctx, func(ctx context.Context, conn *sql.DB) error {
		var db boil.ContextExecutor
		if tx != nil {
			db = tx
		} else {
			db = conn
		}

		rowsAff, err := data.Update(ctx, db, boil.Whitelist(
			model.PromotionCouponTemplateColumns.Status,
			model.PromotionCouponTemplateColumns.DeletedAt,
		))
		if err != nil {
			return err
		}

		if rowsAff == 0 {
			return model.ErrNotUpdated
		}

		return nil
	}, r.getCacheKeys(data)...)

	return err
}

func (r *customCouponTemplateRepository) ForceDelete(
	ctx context.Context,
	tx boil.ContextExecutor,
	id uint64,
) error {
	data, err := r.FindOneNoCache(ctx, tx, id)
	if err != nil {
		if err == model.ErrNotFound {
			return nil
		}

		return err
	}

	err = r.ExecCtx(ctx, func(ctx context.Context, conn *sql.DB) error {
		var db boil.ContextExecutor
		if tx != nil {
			db = tx
		} else {
			db = conn
		}

		rowsAff, err := data.Delete(ctx, db)
		if err != nil {
			return err
		}

		if rowsAff == 0 {
			return model.ErrNotDeleted
		}

		return nil
	}, r.getCacheKeys(data)...)

	return err
}

func (r *customCouponTemplateRepository) ForceDeleteBatch(
	ctx context.Context,
	tx boil.ContextExecutor,
	ids []uint64,
) error {
	if len(ids) > 0 {
		err := r.ExecCtx(ctx, func(ctx context.Context, conn *sql.DB) error {
			var db boil.ContextExecutor
			if tx != nil {
				db = tx
			} else {
				db = conn
			}

			var mods []qm.QueryMod
			mods = append(mods, model.PromotionCouponTemplateWhere.ID.IN(ids))

			rowsAff, err := model.PromotionCouponTemplates(mods...).DeleteAll(ctx, db)
			if err != nil {
				return err
			}

			if rowsAff == 0 {
				return model.ErrNotDeleted
			}

			return nil
		}, r.formatPrimaries(ids)...)

		return err
	}

	return nil
}

func (r *customCouponTemplateRepository) getCacheKeys(data *model.PromotionCouponTemplate) []string {
	if data == nil {
		return []string{}
	}

	cacheIdKey := r.formatPrimary(data.ID)
	cacheNameKey := r.formatNameKey(data.Name)
	cacheKeys := []string{
		cacheIdKey,
		cacheNameKey,
	}

	return cacheKeys
}

func (r *customCouponTemplateRepository) formatPrimary(primary any) string {
	return fmt.Sprintf("%s%v", r.cacheIdPrefix, primary)
}

func (r *customCouponTemplateRepository) formatPrimaries(primaries []uint64) []string {
	var resp []string
	for _, primary := range primaries {
		resp = append(resp, r.formatPrimary(primary))
	}

	return resp
}

func (r *customCouponTemplateRepository) formatNameKey(name string) string {
	return fmt.Sprintf("%s%s", r.cacheNamePrefix, name)
}

func (r *customCouponTemplateRepository) queryPrimary(ctx context.Context, conn *sql.DB, v, primary any) error {
	var uid uint64
	if jsonId, ok := primary.(json.Number); ok {
		if int64Id, err := jsonId.Int64(); err == nil {
			uid = uint64(int64Id)
		} else {
			return err
		}
	}

	data, err := model.FindPromotionCouponTemplate(ctx, conn, uid)
	if err != nil {
		return err
	}

	*v.(*model.PromotionCouponTemplate) = *data

	return nil
}

func (r *customCouponTemplateRepository) GetProductList(
	ctx context.Context,
	cols model.M,
	withCount int,
	filter map[string]map[string][]any,
) (list []*model.PromotionCouponProductRelationship, count int64, err error) {
	var page int
	var pageSize int
	var limit int
	var selectCol string
	var mods []qm.QueryMod
	var nextCount int64
	var previousCount int64
	for k, v := range cols {
		switch k {
		case "page":
			if val, ok := v.(uint64); ok && val > 1 {
				page = int(val)
			}
		case "pageSize":
			if val, ok := v.(uint64); ok && val > 0 {
				pageSize = int(val)
			}
		case "limit":
			if val, ok := v.(uint32); ok && val > 0 {
				limit = int(val)
			}
		case "offset":
			if withCount == 2 {
				if val, ok := v.(uint32); ok && val > 0 {
					mods = append(mods, qm.Offset(int(val)))
					previousCount = 1
				}
			}
		case "preMinId":
			if withCount == 3 {
				if val, ok := v.(uint64); ok && val > 0 {
					mods = append(mods, qm.OrderBy(model.PromotionCouponProductRelationshipColumns.RelationshipID+" DESC"))
					mods = append(mods, model.PromotionCouponProductRelationshipWhere.RelationshipID.LT(val))
					previousCount = 1
				}
			}
		case "preMaxId":
			if withCount == 4 {
				if val, ok := v.(uint64); ok && val > 0 {
					mods = append(mods, qm.OrderBy(model.PromotionCouponProductRelationshipColumns.RelationshipID+" ASC"))
					mods = append(mods, model.PromotionCouponProductRelationshipWhere.RelationshipID.GT(val))
					previousCount = 1
				}
			}
		case "orderBy":
			if withCount != 3 && withCount != 4 {
				if val, ok := v.(string); ok && val != "" {
					mods = append(mods, qm.OrderBy(val))
				}
			}
		case "select":
			if val, ok := v.(string); ok && val != "" {
				selectCol = val
			}
		}
	}

	for key, opMap := range filter {
		switch key {
		case model.PromotionCouponProductRelationshipColumns.RelationshipID:
			mods = append(mods, modelx.GetIntMods(model.PromotionCouponProductRelationshipColumns.RelationshipID, opMap)...)
		case model.PromotionCouponProductRelationshipColumns.CouponID:
			mods = append(mods, modelx.GetIntMods(model.PromotionCouponProductRelationshipColumns.CouponID, opMap)...)
		case model.PromotionCouponProductRelationshipColumns.ProductType:
			mods = append(mods, modelx.GetIntMods(model.PromotionCouponProductRelationshipColumns.ProductType, opMap)...)
		case model.PromotionCouponProductRelationshipColumns.ProductID:
			mods = append(mods, modelx.GetIntMods(model.PromotionCouponProductRelationshipColumns.ProductID, opMap)...)
		case model.PromotionCouponProductRelationshipColumns.SkuID:
			mods = append(mods, modelx.GetIntMods(model.PromotionCouponProductRelationshipColumns.SkuID, opMap)...)
		case model.PromotionCouponProductRelationshipColumns.Sort:
			mods = append(mods, modelx.GetIntMods(model.PromotionCouponProductRelationshipColumns.Sort, opMap)...)
		case model.PromotionCouponProductRelationshipColumns.Status:
			mods = append(mods, modelx.GetIntMods(model.PromotionCouponProductRelationshipColumns.Status, opMap)...)
		}
	}

	if withCount >= 2 {
		if limit > 0 {
			mods = append(mods, qm.Limit(limit+1))
		}
	} else if withCount >= 0 {
		count, err = model.PromotionCouponProductRelationships(mods...).Count(ctx, r.mysqlConn)
		if err != nil {
			return
		}

		if withCount == 0 {
			return
		}

		if pageSize > 0 {
			if page > 1 {
				mods = append(mods, qm.Offset(pageSize*(page-1)))
			}
			mods = append(mods, qm.Limit(pageSize))
		}
	} else {
		if pageSize > 0 {
			if page > 1 {
				mods = append(mods, qm.Offset(pageSize*(page-1)))
			}
			mods = append(mods, qm.Limit(pageSize))
		}
	}

	var columns []string
	if selectCol != "" {
		if selectCol != "," {
			columns = strings.Split(selectCol, ",")
		} else {
			columns = append(columns, model.PromotionCouponProductRelationshipColumns.RelationshipID)
		}
	}
	if len(columns) > 0 {
		mods = append(mods, qm.Select(columns...))
	}

	list, err = model.PromotionCouponProductRelationships(mods...).All(ctx, r.mysqlConn)
	if withCount >= 2 {
		if limit > 0 && len(list) > limit {
			nextCount = 1
			list = list[:limit]
		}
		count = previousCount + nextCount*2
	}

	return
}

func (r *customCouponTemplateRepository) GetProductBrandList(
	ctx context.Context,
	cols model.M,
	withCount int,
	filter map[string]map[string][]any,
) (list []*model.PromotionCouponProductBrandRelationship, count int64, err error) {
	var page int
	var pageSize int
	var limit int
	var selectCol string
	var mods []qm.QueryMod
	var nextCount int64
	var previousCount int64
	for k, v := range cols {
		switch k {
		case "page":
			if val, ok := v.(uint64); ok && val > 1 {
				page = int(val)
			}
		case "pageSize":
			if val, ok := v.(uint64); ok && val > 0 {
				pageSize = int(val)
			}
		case "limit":
			if val, ok := v.(uint32); ok && val > 0 {
				limit = int(val)
			}
		case "offset":
			if withCount == 2 {
				if val, ok := v.(uint32); ok && val > 0 {
					mods = append(mods, qm.Offset(int(val)))
					previousCount = 1
				}
			}
		case "preMinId":
			if withCount == 3 {
				if val, ok := v.(uint64); ok && val > 0 {
					mods = append(mods, qm.OrderBy(model.PromotionCouponProductBrandRelationshipColumns.RelationshipID+" DESC"))
					mods = append(mods, model.PromotionCouponProductBrandRelationshipWhere.RelationshipID.LT(val))
					previousCount = 1
				}
			}
		case "preMaxId":
			if withCount == 4 {
				if val, ok := v.(uint64); ok && val > 0 {
					mods = append(mods, qm.OrderBy(model.PromotionCouponProductBrandRelationshipColumns.RelationshipID+" ASC"))
					mods = append(mods, model.PromotionCouponProductBrandRelationshipWhere.RelationshipID.GT(val))
					previousCount = 1
				}
			}
		case "orderBy":
			if withCount != 3 && withCount != 4 {
				if val, ok := v.(string); ok && val != "" {
					mods = append(mods, qm.OrderBy(val))
				}
			}
		case "select":
			if val, ok := v.(string); ok && val != "" {
				selectCol = val
			}
		}
	}

	for key, opMap := range filter {
		switch key {
		case model.PromotionCouponProductBrandRelationshipColumns.RelationshipID:
			mods = append(mods, modelx.GetIntMods(model.PromotionCouponProductBrandRelationshipColumns.RelationshipID, opMap)...)
		case model.PromotionCouponProductBrandRelationshipColumns.CouponID:
			mods = append(mods, modelx.GetIntMods(model.PromotionCouponProductBrandRelationshipColumns.CouponID, opMap)...)
		case model.PromotionCouponProductBrandRelationshipColumns.ProductBrandID:
			mods = append(mods, modelx.GetIntMods(model.PromotionCouponProductBrandRelationshipColumns.ProductBrandID, opMap)...)
		case model.PromotionCouponProductBrandRelationshipColumns.Sort:
			mods = append(mods, modelx.GetIntMods(model.PromotionCouponProductBrandRelationshipColumns.Sort, opMap)...)
		case model.PromotionCouponProductBrandRelationshipColumns.Status:
			mods = append(mods, modelx.GetIntMods(model.PromotionCouponProductBrandRelationshipColumns.Status, opMap)...)
		}
	}

	if withCount >= 2 {
		if limit > 0 {
			mods = append(mods, qm.Limit(limit+1))
		}
	} else if withCount >= 0 {
		count, err = model.PromotionCouponProductBrandRelationships(mods...).Count(ctx, r.mysqlConn)
		if err != nil {
			return
		}

		if withCount == 0 {
			return
		}

		if pageSize > 0 {
			if page > 1 {
				mods = append(mods, qm.Offset(pageSize*(page-1)))
			}
			mods = append(mods, qm.Limit(pageSize))
		}
	} else {
		if pageSize > 0 {
			if page > 1 {
				mods = append(mods, qm.Offset(pageSize*(page-1)))
			}
			mods = append(mods, qm.Limit(pageSize))
		}
	}

	var columns []string
	if selectCol != "" {
		if selectCol != "," {
			columns = strings.Split(selectCol, ",")
		} else {
			columns = append(columns, model.PromotionCouponProductBrandRelationshipColumns.RelationshipID)
		}
	}
	if len(columns) > 0 {
		mods = append(mods, qm.Select(columns...))
	}

	list, err = model.PromotionCouponProductBrandRelationships(mods...).All(ctx, r.mysqlConn)
	if withCount >= 2 {
		if limit > 0 && len(list) > limit {
			nextCount = 1
			list = list[:limit]
		}
		count = previousCount + nextCount*2
	}

	return
}

func (r *customCouponTemplateRepository) GetProductCategoryList(
	ctx context.Context,
	cols model.M,
	withCount int,
	filter map[string]map[string][]any,
) (list []*model.PromotionCouponProductCategoryRelationship, count int64, err error) {
	var page int
	var pageSize int
	var limit int
	var selectCol string
	var mods []qm.QueryMod
	var nextCount int64
	var previousCount int64
	for k, v := range cols {
		switch k {
		case "page":
			if val, ok := v.(uint64); ok && val > 1 {
				page = int(val)
			}
		case "pageSize":
			if val, ok := v.(uint64); ok && val > 0 {
				pageSize = int(val)
			}
		case "limit":
			if val, ok := v.(int32); ok && val > 0 {
				limit = int(val)
			}
		case "offset":
			if withCount == 2 {
				if val, ok := v.(uint32); ok && val > 0 {
					mods = append(mods, qm.Offset(int(val)))
					previousCount = 1
				}
			}
		case "preMinId":
			if withCount == 3 {
				if val, ok := v.(uint64); ok && val > 0 {
					mods = append(mods, qm.OrderBy(model.PromotionCouponProductCategoryRelationshipColumns.RelationshipID+" DESC"))
					mods = append(mods, model.PromotionCouponProductCategoryRelationshipWhere.RelationshipID.LT(val))
					previousCount = 1
				}
			}
		case "preMaxId":
			if withCount == 4 {
				if val, ok := v.(uint64); ok && val > 0 {
					mods = append(mods, qm.OrderBy(model.PromotionCouponProductCategoryRelationshipColumns.RelationshipID+" ASC"))
					mods = append(mods, model.PromotionCouponProductCategoryRelationshipWhere.RelationshipID.GT(val))
					previousCount = 1
				}
			}
		case "orderBy":
			if withCount != 3 && withCount != 4 {
				if val, ok := v.(string); ok && val != "" {
					mods = append(mods, qm.OrderBy(val))
				}
			}
		case "select":
			if val, ok := v.(string); ok && val != "" {
				selectCol = val
			}
		}
	}

	for key, opMap := range filter {
		switch key {
		case model.PromotionCouponProductCategoryRelationshipColumns.RelationshipID:
			mods = append(mods, modelx.GetIntMods(model.PromotionCouponProductCategoryRelationshipColumns.RelationshipID, opMap)...)
		case model.PromotionCouponProductCategoryRelationshipColumns.CouponID:
			mods = append(mods, modelx.GetIntMods(model.PromotionCouponProductCategoryRelationshipColumns.CouponID, opMap)...)
		case model.PromotionCouponProductCategoryRelationshipColumns.ProductCategoryID:
			mods = append(mods, modelx.GetIntMods(model.PromotionCouponProductCategoryRelationshipColumns.ProductCategoryID, opMap)...)
		case model.PromotionCouponProductCategoryRelationshipColumns.Sort:
			mods = append(mods, modelx.GetIntMods(model.PromotionCouponProductCategoryRelationshipColumns.Sort, opMap)...)
		case model.PromotionCouponProductCategoryRelationshipColumns.Status:
			mods = append(mods, modelx.GetIntMods(model.PromotionCouponProductCategoryRelationshipColumns.Status, opMap)...)
		}
	}

	if withCount >= 2 {
		if limit > 0 {
			mods = append(mods, qm.Limit(limit+1))
		}
	} else if withCount >= 0 {
		count, err = model.PromotionCouponProductCategoryRelationships(mods...).Count(ctx, r.mysqlConn)
		if err != nil {
			return
		}

		if withCount == 0 {
			return
		}

		if pageSize > 0 {
			if page > 1 {
				mods = append(mods, qm.Offset(pageSize*(page-1)))
			}
			mods = append(mods, qm.Limit(pageSize))
		}
	} else {
		if pageSize > 0 {
			if page > 1 {
				mods = append(mods, qm.Offset(pageSize*(page-1)))
			}
			mods = append(mods, qm.Limit(pageSize))
		}
	}

	var columns []string
	if selectCol != "" {
		if selectCol != "," {
			columns = strings.Split(selectCol, ",")
		} else {
			columns = append(columns, model.PromotionCouponProductCategoryRelationshipColumns.RelationshipID)
		}
	}
	if len(columns) > 0 {
		mods = append(mods, qm.Select(columns...))
	}

	list, err = model.PromotionCouponProductCategoryRelationships(mods...).All(ctx, r.mysqlConn)
	if withCount >= 2 {
		if limit > 0 && len(list) > limit {
			nextCount = 1
			list = list[:limit]
		}
		count = previousCount + nextCount*2
	}

	return
}

func (r *customCouponTemplateRepository) AttachProductToCoupon(
	ctx context.Context,
	tx boil.ContextExecutor,
	data *model.CouponProductRelationship,
) error {
	var db boil.ContextExecutor
	if tx != nil {
		db = tx
	} else {
		db = r.mysqlConn
	}

	if data.RelationshipID > 0 {
		_, err := data.Update(ctx, db, boil.Whitelist(
			model.CouponProductRelationshipColumns.Sort,
		))
		if err != nil {
			return err
		}
	} else {
		err := data.Insert(ctx, db, boil.Infer())
		if err != nil {
			return err
		}
	}

	return nil
}

func (r *customCouponTemplateRepository) DetachProductFromCoupon(
	ctx context.Context,
	tx boil.ContextExecutor,
	filter map[string]map[string][]any,
) error {
	var db boil.ContextExecutor
	if tx != nil {
		db = tx
	} else {
		db = r.mysqlConn
	}

	var mods []qm.QueryMod
	for key, opMap := range filter {
		switch key {
		case model.CouponProductRelationshipColumns.RelationshipID:
			mods = append(mods, modelx.GetIntMods(model.CouponProductRelationshipColumns.RelationshipID, opMap)...)
		case model.CouponProductRelationshipColumns.CouponID:
			mods = append(mods, modelx.GetIntMods(model.CouponProductRelationshipColumns.CouponID, opMap)...)
		case model.CouponProductRelationshipColumns.BrandID:
			mods = append(mods, modelx.GetIntMods(model.CouponProductRelationshipColumns.BrandID, opMap)...)
		case model.CouponProductRelationshipColumns.CategoryID:
			mods = append(mods, modelx.GetIntMods(model.CouponProductRelationshipColumns.CategoryID, opMap)...)
		case model.CouponProductRelationshipColumns.ProductID:
			mods = append(mods, modelx.GetIntMods(model.CouponProductRelationshipColumns.ProductID, opMap)...)
		case model.CouponProductRelationshipColumns.ProductType:
			mods = append(mods, modelx.GetIntMods(model.CouponProductRelationshipColumns.ProductType, opMap)...)
		}
	}
	if len(mods) == 0 {
		return nil
	}

	_, err := model.CouponProductRelationships(mods...).DeleteAll(ctx, db)
	return err
}

func (r *customCouponTemplateRepository) GetRelProductList(
	ctx context.Context,
	cols model.M,
	withCount int,
	filter map[string]map[string][]any,
) (list []*model.CouponProductRelationship, count int64, err error) {
	var page int
	var pageSize int
	var limit int
	var selectCol string
	var mods []qm.QueryMod
	var nextCount int64
	var previousCount int64
	for k, v := range cols {
		switch k {
		case "page":
			if val, ok := v.(uint64); ok && val > 1 {
				page = int(val)
			}
		case "pageSize":
			if val, ok := v.(uint64); ok && val > 0 {
				pageSize = int(val)
			}
		case "limit":
			if val, ok := v.(uint32); ok && val > 0 {
				limit = int(val)
			}
		case "offset":
			if withCount == 2 {
				if val, ok := v.(uint32); ok && val > 0 {
					mods = append(mods, qm.Offset(int(val)))
					previousCount = 1
				}
			}
		case "orderBy":
			if val, ok := v.(string); ok && len(val) > 0 {
				mods = append(mods, qm.OrderBy(val))
			}
		case "preMinId":
			if withCount == 3 {
				if val, ok := v.(uint64); ok && val > 0 {
					mods = append(mods, qm.OrderBy(model.CouponProductRelationshipColumns.RelationshipID+" DESC"))
					mods = append(mods, model.CouponProductRelationshipWhere.RelationshipID.LT(val))
					previousCount = 1
				}
			}
		case "preMaxId":
			if withCount == 4 {
				if val, ok := v.(uint64); ok && val > 0 {
					mods = append(mods, qm.OrderBy(model.CouponProductRelationshipColumns.RelationshipID+" ASC"))
					mods = append(mods, model.CouponProductRelationshipWhere.RelationshipID.GT(val))
					previousCount = 1
				}
			}
		case "select":
			if withCount != 5 {
				if val, ok := v.(string); ok && len(val) > 0 {
					selectCol = val
				}
			}
		}
	}

	for key, opMap := range filter {
		switch key {
		case model.CouponProductRelationshipColumns.RelationshipID:
			mods = append(mods, modelx.GetIntMods(model.CouponProductRelationshipColumns.RelationshipID, opMap)...)
		case model.CouponProductRelationshipColumns.CouponID:
			mods = append(mods, modelx.GetIntMods(model.CouponProductRelationshipColumns.CouponID, opMap)...)
		case model.CouponProductRelationshipColumns.BrandID:
			mods = append(mods, modelx.GetIntMods(model.CouponProductRelationshipColumns.BrandID, opMap)...)
		case model.CouponProductRelationshipColumns.CategoryID:
			mods = append(mods, modelx.GetIntMods(model.CouponProductRelationshipColumns.CategoryID, opMap)...)
		case model.CouponProductRelationshipColumns.ProductID:
			mods = append(mods, modelx.GetIntMods(model.CouponProductRelationshipColumns.ProductID, opMap)...)
		case model.CouponProductRelationshipColumns.ProductType:
			mods = append(mods, modelx.GetIntMods(model.CouponProductRelationshipColumns.ProductType, opMap)...)
		}
	}

	if withCount >= 2 {
		if limit > 0 {
			mods = append(mods, qm.Limit(limit+1))
		}
	} else if withCount >= 0 {
		count, err = model.CouponProductRelationships(mods...).Count(ctx, r.mysqlConn)
		if err != nil {
			return
		}

		if withCount == 0 {
			return
		}
	}

	if pageSize > 0 && (withCount == -1 || withCount == 1) {
		if page > 1 {
			mods = append(mods, qm.Offset(pageSize*(page-1)))
		}
		mods = append(mods, qm.Limit(pageSize))
	}

	var columns []string
	if len(selectCol) > 0 {
		if selectCol == "," {
			columns = append(columns, model.CouponProductRelationshipColumns.RelationshipID)
		} else {
			columns = strings.Split(selectCol, ",")
		}
	}
	if len(columns) > 0 {
		mods = append(mods, qm.Select(columns...))
	}

	list, err = model.CouponProductRelationships(mods...).All(ctx, r.mysqlConn)
	if err != nil {
		return
	}

	if withCount >= 2 {
		if limit > 0 && len(list) > limit {
			nextCount = 1
			list = list[:limit]
		}
		count = previousCount + nextCount*2
	}

	return
}

func (r *customCouponTemplateRepository) UpdateBindRel(
	ctx context.Context,
	tx boil.ContextExecutor,
	id uint64,
	rel *model.PromotionCouponBindRel,
) error {
	if rel == nil {
		return nil
	}

	var db boil.ContextExecutor
	if tx != nil {
		db = tx
	} else {
		db = r.mysqlConn
	}

	if len(rel.Products) > 0 {
		for _, relationShip := range rel.Products {
			relationShip.CouponID = id
			err := relationShip.Insert(ctx, db, boil.Infer())
			if err != nil {
				return err
			}
		}
	}

	if len(rel.DelSkuIds) > 0 {
		var mods []qm.QueryMod
		mods = append(mods, model.PromotionCouponProductRelationshipWhere.CouponID.EQ(id))
		mods = append(mods, model.PromotionCouponProductRelationshipWhere.SkuID.IN(rel.DelSkuIds))
		_, err := model.PromotionCouponProductRelationships(mods...).DeleteAll(ctx, db)
		if err != nil {
			return err
		}
	}

	if len(rel.Brands) > 0 {
		for _, relationShip := range rel.Brands {
			relationShip.CouponID = id
			err := relationShip.Insert(ctx, db, boil.Infer())
			if err != nil {
				return err
			}
		}
	}

	if len(rel.DelBrandIds) > 0 {
		var mods []qm.QueryMod
		mods = append(mods, model.PromotionCouponProductBrandRelationshipWhere.CouponID.EQ(id))
		mods = append(mods, model.PromotionCouponProductBrandRelationshipWhere.ProductBrandID.IN(rel.DelBrandIds))
		_, err := model.PromotionCouponProductBrandRelationships(mods...).DeleteAll(ctx, db)
		if err != nil {
			return err
		}
	}

	if len(rel.Categories) > 0 {
		for _, relationShip := range rel.Categories {
			relationShip.CouponID = id
			err := relationShip.Insert(ctx, db, boil.Infer())
			if err != nil {
				return err
			}
		}
	}

	if len(rel.DelCategoryIds) > 0 {
		var mods []qm.QueryMod
		mods = append(mods, model.PromotionCouponProductCategoryRelationshipWhere.CouponID.EQ(id))
		mods = append(mods, model.PromotionCouponProductCategoryRelationshipWhere.ProductCategoryID.IN(rel.DelCategoryIds))
		_, err := model.PromotionCouponProductCategoryRelationships(mods...).DeleteAll(ctx, db)
		if err != nil {
			return err
		}
	}

	return nil
}

func (r *customCouponTemplateRepository) GetMedia(
	ctx context.Context,
	cols model.M,
	withCount int,
	filter map[string]map[string][]any,
) (list []*model.PromotionAttachmentRelationship, count int64, err error) {
	var page int
	var pageSize int
	var limit int
	var selectCol string
	var mods []qm.QueryMod
	var nextCount int64
	var previousCount int64
	for k, v := range cols {
		switch k {
		case "page":
			if val, ok := v.(uint64); ok && val > 1 {
				page = int(val)
			}
		case "pageSize":
			if val, ok := v.(uint64); ok && val > 0 {
				pageSize = int(val)
			}
		case "limit":
			if val, ok := v.(uint32); ok && val > 0 {
				limit = int(val)
			}
		case "offset":
			if withCount == 2 {
				if val, ok := v.(uint32); ok && val > 0 {
					mods = append(mods, qm.Offset(int(val)))
					previousCount = 1
				}
			}
		case "orderBy":
			if val, ok := v.(string); ok && len(val) > 0 {
				mods = append(mods, qm.OrderBy(val))
			}
		case "preMinId":
			if withCount == 3 {
				if val, ok := v.(uint64); ok && val > 0 {
					mods = append(mods, qm.OrderBy(model.PromotionAttachmentRelationshipColumns.AttachmentRelationshipID+" DESC"))
					mods = append(mods, model.PromotionAttachmentRelationshipWhere.AttachmentRelationshipID.LT(val))
					previousCount = 1
				}
			}
		case "preMaxId":
			if withCount == 4 {
				if val, ok := v.(uint64); ok && val > 0 {
					mods = append(mods, qm.OrderBy(model.PromotionAttachmentRelationshipColumns.AttachmentRelationshipID+" ASC"))
					mods = append(mods, model.PromotionAttachmentRelationshipWhere.AttachmentRelationshipID.GT(val))
					previousCount = 1
				}
			}
		case "select":
			if withCount != 5 {
				if val, ok := v.(string); ok && len(val) > 0 {
					selectCol = val
				}
			}
		}
	}

	for key, opMap := range filter {
		switch key {
		case model.PromotionAttachmentRelationshipColumns.AttachmentRelationshipID:
			mods = append(mods, modelx.GetIntMods(model.PromotionAttachmentRelationshipColumns.AttachmentRelationshipID, opMap)...)
		case model.PromotionAttachmentRelationshipColumns.ObjectID:
			mods = append(mods, modelx.GetIntMods(model.PromotionAttachmentRelationshipColumns.ObjectID, opMap)...)
		case model.PromotionAttachmentRelationshipColumns.ObjectType:
			mods = append(mods, modelx.GetIntMods(model.PromotionAttachmentRelationshipColumns.ObjectType, opMap)...)
		case model.PromotionAttachmentRelationshipColumns.AttachmentID:
			mods = append(mods, modelx.GetIntMods(model.PromotionAttachmentRelationshipColumns.AttachmentID, opMap)...)
		case model.PromotionAttachmentRelationshipColumns.AttachmentThumbnail:
			mods = append(mods, modelx.GetIntMods(model.PromotionAttachmentRelationshipColumns.AttachmentThumbnail, opMap)...)
		case model.PromotionAttachmentRelationshipColumns.AttachmentOrder:
			mods = append(mods, modelx.GetIntMods(model.PromotionAttachmentRelationshipColumns.AttachmentOrder, opMap)...)
		case model.PromotionAttachmentRelationshipColumns.AttachmentSource:
			mods = append(mods, modelx.GetStringMods(model.PromotionAttachmentRelationshipColumns.AttachmentSource, opMap)...)
		case model.PromotionAttachmentRelationshipColumns.AttachmentImageURL:
			mods = append(mods, modelx.GetStringMods(model.PromotionAttachmentRelationshipColumns.AttachmentImageURL, opMap)...)
		case model.PromotionAttachmentRelationshipColumns.AttachmentImageAlt:
			mods = append(mods, modelx.GetStringMods(model.PromotionAttachmentRelationshipColumns.AttachmentImageAlt, opMap)...)
		}
	}

	if withCount >= 2 {
		if limit > 0 {
			mods = append(mods, qm.Limit(limit+1))
		}
	} else if withCount >= 0 {
		count, err = model.PromotionAttachmentRelationships(mods...).Count(ctx, r.mysqlConn)
		if err != nil {
			return
		}

		if withCount == 0 {
			return
		}
	}

	if pageSize > 0 && (withCount == -1 || withCount == 1) {
		if page > 1 {
			mods = append(mods, qm.Offset(pageSize*(page-1)))
		}
		mods = append(mods, qm.Limit(pageSize))
	}

	var columns []string
	if len(selectCol) > 0 {
		if selectCol == "," {
			columns = append(columns, model.PromotionAttachmentRelationshipColumns.AttachmentRelationshipID)
		} else {
			columns = strings.Split(selectCol, ",")
		}
	}
	if len(columns) > 0 {
		mods = append(mods, qm.Select(columns...))
	}

	list, err = model.PromotionAttachmentRelationships(mods...).All(ctx, r.mysqlConn)
	if err != nil {
		return
	}

	if withCount >= 2 {
		if limit > 0 && len(list) > limit {
			nextCount = 1
			list = list[:limit]
		}
		count = previousCount + nextCount*2
	}

	return
}

func (r *customCouponTemplateRepository) GetMeta(
	ctx context.Context,
	cols model.M,
	withCount int,
	filter map[string]map[string][]any,
) (list []*model.PromotionCouponMetum, count int64, err error) {
	var page int
	var pageSize int
	var limit int
	var selectCol string
	var mods []qm.QueryMod
	var nextCount int64
	var previousCount int64
	for k, v := range cols {
		switch k {
		case "page":
			if val, ok := v.(uint64); ok && val > 1 {
				page = int(val)
			}
		case "pageSize":
			if val, ok := v.(uint64); ok && val > 0 {
				pageSize = int(val)
			}
		case "limit":
			if val, ok := v.(uint32); ok && val > 0 {
				limit = int(val)
			}
		case "offset":
			if withCount == 2 {
				if val, ok := v.(uint32); ok && val > 0 {
					mods = append(mods, qm.Offset(int(val)))
					previousCount = 1
				}
			}
		case "orderBy":
			if val, ok := v.(string); ok && len(val) > 0 {
				mods = append(mods, qm.OrderBy(val))
			}
		case "preMinId":
			if withCount == 3 {
				if val, ok := v.(uint64); ok && val > 0 {
					mods = append(mods, qm.OrderBy(model.PromotionCouponMetumColumns.MetaID+" DESC"))
					mods = append(mods, model.PromotionCouponMetumWhere.MetaID.LT(val))
					previousCount = 1
				}
			}
		case "preMaxId":
			if withCount == 4 {
				if val, ok := v.(uint64); ok && val > 0 {
					mods = append(mods, qm.OrderBy(model.PromotionCouponMetumColumns.MetaID+" ASC"))
					mods = append(mods, model.PromotionCouponMetumWhere.MetaID.GT(val))
					previousCount = 1
				}
			}
		case "select":
			if withCount != 5 {
				if val, ok := v.(string); ok && len(val) > 0 {
					selectCol = val
				}
			}
		}
	}

	for key, opMap := range filter {
		switch key {
		case model.PromotionCouponMetumColumns.MetaID:
			mods = append(mods, modelx.GetIntMods(model.PromotionCouponMetumColumns.MetaID, opMap)...)
		case model.PromotionCouponMetumColumns.CouponTemplateID:
			mods = append(mods, modelx.GetIntMods(model.PromotionCouponMetumColumns.CouponTemplateID, opMap)...)
		case model.PromotionCouponMetumColumns.MetaKey:
			mods = append(mods, modelx.GetStringMods(model.PromotionCouponMetumColumns.MetaKey, opMap)...)
		case model.PromotionCouponMetumColumns.MetaValue:
			mods = append(mods, modelx.GetIntMods(model.PromotionCouponMetumColumns.MetaValue, opMap)...)
		}
	}

	if withCount >= 2 {
		if limit > 0 {
			mods = append(mods, qm.Limit(limit+1))
		}
	} else if withCount >= 0 {
		count, err = model.PromotionCouponMeta(mods...).Count(ctx, r.mysqlConn)
		if err != nil {
			return
		}

		if withCount == 0 {
			return
		}
	}

	if pageSize > 0 && (withCount == -1 || withCount == 1) {
		if page > 1 {
			mods = append(mods, qm.Offset(pageSize*(page-1)))
		}
		mods = append(mods, qm.Limit(pageSize))
	}

	var columns []string
	if len(selectCol) > 0 {
		if selectCol == "," {
			columns = append(columns, model.PromotionCouponMetumColumns.MetaID)
		} else {
			columns = strings.Split(selectCol, ",")
		}
	}
	if len(columns) > 0 {
		mods = append(mods, qm.Select(columns...))
	}

	list, err = model.PromotionCouponMeta(mods...).All(ctx, r.mysqlConn)
	if err != nil {
		return
	}

	if withCount >= 2 {
		if limit > 0 && len(list) > limit {
			nextCount = 1
			list = list[:limit]
		}
		count = previousCount + nextCount*2
	}

	return
}
